<template>
	<view class="content">
		<view class="top-bar">
			<view class="top-bar-left" @tap="back()">
				<image src="../../static/images/common/back.png" class="back-img"></image>
			</view>
			<view class="top-bar-center">
				<view class="title">
					<!-- 鱼香肉丝没有鱼 -->
					{{chatNickname}}
				</view>
			</view>
			<view class="top-bar-right">
				<view class="more-img">
					<image src="../../static/images/userInfo/more@2x.png" ></image>
				</view>
				<!-- <view class="group-img">
					
				</view> -->
			</view>
		</view>
		<scroll-view class="chat" scroll-y="true" scroll-with-animation="true" :scroll-into-view="scrollToView">
			<!-- <scroll-view scroll-y="true" @scroll="scrollHandler" class="chat"  :scroll-top="contentHeight"> -->
			<view class="chat-main" :style="{paddingBottom:inputh+'px'}">
				<view class="chat-ls" v-for="(item,index) in getChatHistory(this.to)" :key="index" :id="'msg'+index">
					<view class="chat-time" v-if="item.time!= ''">
						{{changeTime(item.time)}}
					</view>
					<view class="msg-m msg-left" v-show="item.username != userInfo.username">
						<image :src="item.profilePhoto"
							class="user-img user-head-img-left" @tap="toLookUserInfo(item.username)"></image>
							<!-- 文字 -->
						<view class="message" v-if="item.types == 0">
							<view class="nickname" v-show="chatType == 'public'">{{item.nickname}}</view>
							<view class="msg-text msg-text-l">
								{{item.message}}
							</view>
						</view>
						<!-- 图片 -->
						<view class="message" v-else-if="item.types == 1" >
							<image :src="item.message" mode="widthFix" class="msg-img"  @tap="previewImg(item.message)"></image>
						</view>
						<!-- 音频 -->
						<view class="message" v-else-if="item.types == 2" >
							<view class="msg-text voice" :style="{width:item.message.length*10+'px'}" :id="'sound' + index" @tap="playRecord(item.message.voice,'sound' + index,item.message.length)">
								<image :src="soundId == 'sound' + index ? playingImg : playImg"  class="voice-img"></image>
								{{item.message.length}}″
							</view>
						</view>
						
						<!-- 定位 -->
						<view class="message" v-else-if="item.types == 3">
							<view class="msg-text msg-map">
								<view class="map-name">
									{{item.message.name}}
								</view>
								<view class="map-address">
									{{item.message.address}}
								</view>
								<map class="map" :latitude="item.message.latitude" :longitude="item.message.longitude" :markers="covers(item.message)"></map>
							</view>
						
						</view>
					</view>

					<view class="msg-m msg-right" v-show="item.username == userInfo.username">
						<image :src="userInfo.profilePhoto"
							class="user-img user-head-img-right"></image>
						<view class="message" v-if="item.types == 0">
							<view class="msg-text">
								{{item.message}}
							</view>
						</view>
						<view class="message" v-else-if="item.types == 1">
							<image :src="item.message" mode="widthFix" class="msg-img" @tap="previewImg(item.message)"></image>
						</view>
						<!-- 音频 -->
						<view class="message" v-else-if="item.types == 2" :id="'sound' + index" @tap="playRecord(item.message.voice,'sound' + index,item.message.length)">
							<view class="msg-text voice" :style="{width:item.message.length*10+'px'}">
								{{item.message.length}}″
								<image :src="soundId == 'sound' + index ? playingImg : playImg"  class="voice-img"></image>
							</view>
						</view>
						
						<!-- 定位 -->
						<view class="message" v-else-if="item.types == 3">
							<view class="msg-text msg-map">
								<view class="map-name">
									{{item.message.name}}
								</view>
								<view class="map-address">
									{{item.message.address}}
								</view>
								<map class="map" :latitude="item.message.latitude" :longitude="item.message.longitude" :markers="covers(item.message)"></map>
							</view>
							
						</view>
					</view>
				</view>
			</view>
			<!-- <view class="padbt">
				
			</view> -->
		</scroll-view>
		<submit @userMsg = "userMessage" @heights="heights"></submit>
	</view>
</template>

<script>
	import { mapGetters } from 'vuex';
	import datas from '../../commons/js/data.js';
	import myfun from '../../commons/js/myfun.js';
	import submit from '../../components/submit/submit.vue'
	import request from '../../api/request.js';
	const innerAudioContext = uni.createInnerAudioContext();
	export default {
		data() {
			return {
				msgs: [],
				imgMsg:[],
				oldTime:new Date(),
				scrollToView:'',
				inputh:'60',
				contentHeight: 0, //聊天区域的高度
				from:'',
				to:'',
				userInfo:{},
				chatType:'',
				chatNickname:'',
				playImg: '/static/images/chat/audio2.png', //展示音频的img
				playingImg: '', //播放音频的是img
				interval:null,
				palyTimer: null, //监听录音播放结束的timer
				soundId: '', //点击播放的音频id
				//friendName:''
			}
		},
		components:{
			submit,
		},
		// onShow() {
		// 	console.log("onShow")
			
		// 	console.log("用户信息,",this.userInfo)
			
		// },
		onLoad(info) {
			this.from = info.from
			this.to = info.to
			this.create()
			
			this.chatNickname = info.nickname
			this.chatType = info.chatType,
			this.$store.commit('changeChatType', this.chatType);
			this.$store.commit('changeChatId', this.to);
			//this.$store.commit('changeUser', uni.getStorageSync("userInfo"));
			//this.friendName = info.friend
			//console.log(this.from)
			this.userInfo =this.$store.getters.getUser
			//this.getMsg()
			if(this.$store.getters.getChatHistoryItem(this.to)!=null){
				this.msgs = this.$store.getters.getChatHistory(this.to)
				this.addImgPreviewList()
	
			}
			//this.msgs = datas.message()
			
		},
		onShow() {
			//this.$s
			this.goBottom()
		},
		computed:{
		...mapGetters(['getChatHistory']),
		},
		watch: {
		   //  '$store.state.chatHistory': function () {
		   //    //你需要执行的代码
			  // console.log("成功！")
		   //  },
			  //  immediate: true,
			  //       deep: true
		  },
		methods: {
			create(){
				if(this.$store.getters.getChatHistoryItem(this.to)==null){
					//console.log(this.to)
					this.$store.dispatch('addHistoryListItem', this.to);
				}
			},
			//输入框高度
			heights(e){
				this.inputh = e;
				this.goBottom()
			},
			//滚动到底部
			goBottom(){
				this.scrollToView = '',
				this.$nextTick(function(){
					 this.scrollToView = 'msg' +(this.msgs.length - 1);
					 })
			},
			back() {
				this.$store.commit('changeChatId','null');
				uni.navigateBack({
					delta:1
				})
			},
			//处理时间
			changeTime(date) {
				return myfun.dateTime2(date);
			},
			
		 async getMsg() {
				//this.msgs = datas.message();
				//this.friendList = data.friends();
				console.log(this.to)
				console.log("获取消息!")
						let res = await request({
							url: '/message?from='+this.from+"&to="+this.to+"&chatType="+this.chatType,
							method: 'GET'
						});
						res = res[1].data;
						console.log(res)
						//console.log(res.messageContent)
						//this.msgs = JSON.parse(res.messageContent)
						for(var j=0;j<res.data.length;j++){
							var msgs = res.data[j].messageContent
							msgs =  JSON.parse(msgs)
							 res.data[j].messageContent = msgs
			 				//this.msgs.push(JSON.parse(msgs))
							this.$store.commit("updateChatMsg",res.data[j])
							}
				let i;
				for( i=0;i<this.$store.getters.getChatHistory(this.to).length;i++){
					//时间间隔
					if(i!=0){
						let t = myfun.spaceTime(this.oldTime,this.msgs[i].time)
						if(t){
							this.oldTime = t;
						}
						this.$store.getters.getChatHistory(this.to)[i].time = t;
					}
					if(this.$store.getters.getChatHistory(this.to)[i].types == 1)
					this.imgMsg.push(this.$store.getters.getChatHistory(this.to)[i].message)
				}


				this.$nextTick(function(){
					//this.scrollToView = 'msg' + (this.msgs.length - 1);
				this.scrollToView  = 'msg'+	(this.$store.getters.getChatHistory(this.to).length - 1);
					// console.log(this.msgs.length - 1)
				})
			},
			previewImg(selectImg) {
				// 预览图片
				//console.log(this.imgMsg)
				uni.previewImage({
					urls: this.imgMsg,
					current:selectImg,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			userMessage(e){
				//console.log(e)
				if(e.types === 1){//图片
				//console.log("有图片来了！",e.msgs)
					this.imgMsg.push(e.msgs)
				}
			 let newMessage =	{
					chatType: this.chatType,
					fromUser: this.from,
					id: "0",
					messageContent:{
						username:this.userInfo.username,//用户id
						profilePhoto:this.userInfo.profilePhoto,
						message:e.msgs,
						types:e.types,  //区分聊天信息的类型   文本  图片  语音  位置   
						time:new Date(),
						tip:1,
						nickname:this.userInfo.nickname
					},
					messageType: 0,  //区分是聊天信息还是好友请求
					profilePhoto: null,
					sendTime: new Date(),
					toUser: this.to
				}
				var dataMsg = {
					msg:newMessage,
					msg_list:this.$store.getters.getChatHistory(this.to)
				}
				
				
				this.$store.commit("updateChatMsg",dataMsg)
				this.$store.commit("changDialogueInfo",newMessage)
				
				
				this.sendMsg(newMessage)
				this.goBottom()
			},// 窗口动画
		
			sendMsg(info){
				//console.log("发送的信息为："+info)
					  var Msg = {
					      "message": info,
					      "username": this.from,
					      "to": this.to
					  };
					  console.log("发送的信息为：",Msg)
					//that.$websocket  
				this.$store.dispatch('webSocketSend', Msg);
					  //this.websock.send(JSON.stringify(Msg))		  
			},
			//音频播放
			playRecord(url,id,length){
				clearInterval(this.interval);
				clearTimeout(this.palyTimer);
				let index = 0;
				if (this.soundId == id) {
						innerAudioContext.stop();
						innerAudioContext.src = '';
						this.soundId = '';
						this.playingImg = '';
						index = 0;
					} else {
						this.soundId = id;
						innerAudioContext.src = url;
						innerAudioContext.play();
						this.interval = setInterval(() => {
							index++;
							this.playingImg = '/static/images/chat/audio' + (index % 3) + '.png';
						}, 400);
						this.palyTimer = setTimeout(() => {
							clearInterval(this.interval);
							clearTimeout(this.palyTimer);
							this.playingImg = '';
							this.soundId = '';
							index = 0;
						}, length * 1000 + 100);
					}
				
			},
			covers(e){
				let map = [{
					latitude:e.latitude,
					longitude: e.longitude,
					iconPath:'../../static/images/chatroom/dw.png',
				}]
				return map;
			},
			addImgPreviewList(){
				for(var i=0;i<this.msgs.length;i++){
					if(this.msgs[i].types ==1){
						this.imgMsg.push(this.msgs[i].message)
					}
				}
				console.log(this.imgMsg)
			},
			toLookUserInfo(username){
				console.log(username)
				var tip = this.isFriend(username)
				if(tip != 1){
					uni.navigateTo({
						url:"../userInfo/userInfo?isFriend=no&username="+username
					})
				}
				else{
					uni.navigateTo({
						url:"../userInfo/userInfo?isFriend=yes&username="+username
					})
				}
			},
			//判断是否为好友
			isFriend(username){
				let tip = 0;
				let arr = this.$store.state.friends;
				for(let i=0;i<arr.length;i++){
					if(arr[i].username == username){
						tip = 1;
					}
				}
				return tip
			},
			
		}
	}
</script>

<style lang="scss">
	@import "../../commons/css/mycss.scss";

	page {
		height: 100%;
	}
	.content {
		height: 100%;
		background-color: rgba(244, 244, 244, 1);
	}

	.top-bar {
		background-color: rgba(244, 244, 244, 0.96);
		border-bottom: 1px solid $uni-border-color;

		.top-bar-left {
			float: left;
			padding-left: 32rpx;
			// background-color: #eee;
			width: 88rpx;
			height: 88rpx;

			.back-img {
				margin-top: 21rpx;
				width: 46rpx;
				height: 46rpx;
			}
		}

		.title {
			margin-top: env(safe-area-inset-top);
			font-size: 35rpx;
			font-family: PingFangSC-Regular;
			// padding-top: 20rpx;
			line-height: 88rpx;
		}

		.group-img {
			position: absolute;
			bottom: 10rpx;
			right: $uni-spacing-col-base;
			width: 68rpx;
			height: 68rpx;

			image {
				width: 68rpx;
				height: 68rpx;
				border-radius: 16rpx;
			}

		}
	}

	.chat {
		height: 100%;
		.padbt{
			 height: env(safe-area-inset-bottom);
			 width: 100%;
		}
		.chat-main {
			padding-left: $uni-spacing-col-base;
			padding-right: $uni-spacing-col-base;
			padding-top: 100rpx;
			display: flex;
			flex-direction: column;
			font-family: PingFangSC-Regular;
		}

		.chat-ls {
			.chat-time {
				font-size: 24rpx;
				color: rgba(39, 40, 50, 0.3);
				line-height: 34rpx;
				padding: 20rpx 0;
				text-align: center;
			}

			.msg-m {
				display: flex;
				padding: 20rpx 0;

				.user-img {
					flex: none;
					width: 80rpx;
					height: 80rpx;
					border-radius: 20rpx;
				}

				.message {
					flex: none;
					max-width: 480rpx;

				}
				
				.msg-text {
					max-width: 480rpx;
					// 还有一个小点：.message这个盒子限制了max-width:480rpx;    这个只套住了中文如果是纯英文或者数字并且很长的内容的话  依旧不会自动换行，然后我这边做的调整就是对公共的.msg-text这个盒子  新增了几个样式分别为：max-width: 480rpx;
				/*这两行代码可以解决大部分场景下的换行问题*/
					word-break: break-all;
					word-wrap: break-word;
					/*但在有些场景中，还需要加上下面这行代码*/
					white-space: normal;
	
					font-size: 32rpx;
					color: #272832;
					line-height: 44rpx;
					padding: 18rpx 24rpx;
				}
				.msg-img {
					max-width: 400rpx;
					border-radius: 20rpx;
				}
					
				.msg-map{
					// background-color: #fff;
					// width: 464rpx;
					// height: 284rpx;
					// overflow: hidden;
					.map-name{
						font-size: 32rpx;
						color: #272832;
						line-height: 44rpx;
						padding: 18rpx 24rpx 0 24rpx;
						display: -webkit-box;
						 -webkit-box-orient:vertical;
						 -webkit-line-clamp:1;
						 overflow: hidden;
					}
					.map-address{
						font-size: $uni-font-size-sm;
						color: $uni-text-color-disable;
						line-height: 44rpx;
						padding: 0 24rpx;
						display: -webkit-box;
						 -webkit-box-orient:vertical;
						 -webkit-line-clamp:1;
						 overflow: hidden;
					}
					.map{
						width: 464rpx;
						height: 200rpx;
					}
				}
				.voice{
					width: 200rpx;
					min-width: 70rpx;
					max-width: 60%;
				}
				.voice-img{
					width: 64rpx;
					height: 64rpx;
				}
			}

			

			.msg-left {
				flex-direction: row;

				// .msg-text {
				// 	margin-left: 16rpx;
				// 	background-color: #fff;
				// 	border-radius: 10rpx 10rpx 10rpx 10rpx;
				// }
				.nickname{
					margin-top: -15rpx;
					color: #5C5A56;
					font-size: 10rpx;
					margin-left: 25rpx;
				}
				.msg-text {
					float: left;
					margin-left: 25rpx;
					border-radius: 10rpx;
					padding: 16rpx 10rpx;
					max-width: 60%;
					background: #FFFFFF;
					font-size: 30rpx;
					min-height: 40rpx;
					line-height: 40rpx;
					position: relative;
				}
				.msg-text {
					max-width: 100%;
				}
				/* 箭头 */
				.msg-text::before {
					content: '';
					width: 0;
					height: 0;
					position: absolute;
					left: -14rpx;
					top: 12px;
					border-top: solid 16rpx transparent;
					border-right: solid 16rpx #FFFFFF; /* 黑色大三角形 */
					border-bottom: solid 16rpx transparent;
				}
			

				.msg-img {
					margin-left: 16rpx;
				}
				.msg-map{
					margin-left: 16rpx;
				}
				.voice{
				text-align: left;
					
				}
					
				.voice-img{
					float: left;
				
					width: 32rpx;
					height: 32rpx;
					// padding-bottom: 4rpx;
					margin-right: 5rpx;
					padding-top: 4rpx;
				}
			}

			.msg-right {
				flex-direction: row-reverse;
				
				// .msg-text {
				// 	margin-right: 16rpx;
				// 	background-color: #fff260;
				// 	border-radius: 10rpx 10rpx 10rpx 10rpx;
				// }
				// .msg-text:after{
				// 	content: '';
				// 	width: 100px;
				// 	height: 100px;
				// 	position: absolute;
				// 	right: -14rpx;
				// 	top: 12px;
				// 	border-top: solid 16rpx transparent;
				// 	border-left: solid 16rpx #9eea6a; /* 黑色大三角形 */
				// 	border-bottom: solid 16rpx transparent;
				// }
				.msg-text {
					float: right;
					margin-right: 25rpx;
					border-radius: 10rpx;
					padding: 16rpx 10rpx;
					max-width: 60%;
					background: $uni-color-primary;
					font-size: 30rpx;
					min-height: 40rpx;
					line-height: 40rpx;
					position: relative;
				}
				.msg-text {
					max-width: 100%;
				}
				/* 箭头 */
				.msg-text:after {
					content: '';
					width: 0;
					height: 0;
					position: absolute;
					right: -14rpx;
					top: 12px;
					border-top: solid 16rpx transparent;
					border-left: solid 16rpx $uni-color-primary; /* 黑色大三角形 */
					border-bottom: solid 16rpx transparent;
				}
				.msg-img {
					margin-right: 16rpx;
				}
				
				.msg-map{
					margin-right: 16rpx;
				}
				.voice{
				text-align: right;
					
				}
				.voice-img{
					transform: rotate(180deg);
					float: right;
					width: 32rpx;
					height: 32rpx;
					padding-top: 4rpx;
					margin-left: 5rpx;
				}
			}
		}
	}
</style>
